class Solution {
    int[][] nextPostition = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int oldColor = image[sr][sc];
        int row = image.length;
        int col = image[0].length;

        if(oldColor != newColor){
            Dfs(image, row, col, sr, sc, oldColor, newColor);
        }

        return image;

    }
    //记录坐标image[sr][sc]四个方向像素值与其相同的点,将其改为newColor
    public void dfs(int[][] image, int row, int col, int sr, int sc, int oldColor, int newColor){
        image[sr][sc] = newColor;
        
        for(int i = 0; i < 4; i++){
            int newSr = sr + nextPostition[i][0];
            int newSc = sc + nextPostition[i][1];
            //判断下标是否越界
            if(newSr >= row || newSr < 0 || newSc >= col || newSc < 0){
                continue;
            }
            //如果颜色符合要求，则继续渲染
            if(image[newSr][newSc] == oldColor){
                Dfs(image, row, col, newSr, newSc, oldColor, newColor);
            }
        }
    }
}